<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function concurRequest(urlArr, maxNum) {
            return new Promise(function (resolve, reject) {
                if (urlArr.length === 0) { //如果是空请求数组,直接阻止代码向下执行并且返回空数据
                    resolve([]);
                    return;
                }
                let results = []; //存放结果的数组
                let index = 0; //当前请求数组中的下标
                let count = 0; //执行完成请求的个数
                async function request() {
                    if (index === urlArr.length) {
                        return
                    }
                    let idx = index; //存放结果数据的下标
                    let url = urlArr[index]; //将要发送请求的地址
                    index++;
                    try {
                        let data = await fetch(url);
                        results[idx] = data.json(); //将成功返回的结果存放到结果数组中
                    } catch (err) {
                        results[idx] = err; //将失败返回的错误信息存放到结果数组中
                    } finally {
                        count++;
                        if (count === urlArr.length) {//如果count个数等于请求数组的长度说明所有请求执行完毕
                            console.log("over");
                            resolve(results); //返回结果数组
                        }
                        request() //继续执行下次请求
                    }
                }
                let times = Math.min(urlArr.length, maxNum);
                for (let i = 0; i < times; i++) {
                    request()
                }
            })


        }



        let urls = []
        for (let i = 1; i <= 10; i++) {
            urls.push(`https://jsonplaceholder.typicode.com/todos/${i}`)
        }
        concurRequest(urls, 3).then(res => {
            console.log(res);
            // res.forEach(itm=>{
            //     itm.then(data=>{
            //         console.log(data);
            //     })
            // })
        })
    </script>
</body>

</html>